import React, { useState, useRef, useEffect } from 'react'
import styled from 'styled-components'

const AppContainer = styled.div`
  width: 100vw;
  height: 100vh;
  background-color: #0a0a0a;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 20px;
  position: relative;
  overflow: hidden;
`

const ConfigContainer = styled.div`
  width: 80%;
  background-color: #000;
  border: 1px solid #1a1a1a;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
`

const ConfigItem = styled.div`
  display: flex;
  align-items: center;
  gap: 10px;
  color: #0f0;
`

const Label = styled.label`
  color: #0f0;
  font-size: 14px;
`

const Input = styled.input`
  background-color: #1a1a1a;
  border: 1px solid #2a2a2a;
  border-radius: 4px;
  color: #0f0;
  padding: 5px;
  width: ${props => props.type === 'file' ? '200px' : '60px'};
  &::-webkit-color-swatch {
    border: none;
    border-radius: 2px;
  }
`

const EditorContainer = styled.div`
  width: 80%;
  height: 50%;
  background-color: #000;
  border: 1px solid #1a1a1a;
  border-radius: 8px;
  position: relative;
  box-shadow: 0 0 20px rgba(0, 255, 0, 0.1);
  margin-bottom: 20px;
`

const TextArea = styled.textarea`
  width: 100%;
  height: 100%;
  background-color: #000;
  color: #0f0;
  font-family: 'Courier New', monospace;
  padding: 20px;
  border: none;
  resize: none;
  &:focus {
    outline: none;
  }
`

const ButtonContainer = styled.div`
  width: 80%;
  display: flex;
  gap: 20px;
  justify-content: center;
`

const Button = styled.button`
  background-color: #1a1a1a;
  border: 1px solid #2a2a2a;
  border-radius: 4px;
  color: #0f0;
  padding: 10px 20px;
  cursor: pointer;
  font-family: 'Courier New', monospace;
  transition: all 0.3s ease;

  &:hover {
    background-color: #2a2a2a;
    border-color: #0f0;
  }
`

const PreviewContainer = styled.div`
  width: 80%;
  height: 300px;
  background-color: #000;
  border: 1px solid #1a1a1a;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
`

const Canvas = styled.canvas`
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
  visibility: hidden;
`

const PreviewCanvas = styled.canvas`
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  display: block;
`

function App() {
  const [selectedFile, setSelectedFile] = useState(null)
  const [subtitleHeight, setSubtitleHeight] = useState(40)
  const [fontSize, setFontSize] = useState(20)
  const [fontColor, setFontColor] = useState('#ffffff')
  const [outlineColor, setOutlineColor] = useState('#000000')
  const [subtitleText, setSubtitleText] = useState('')
  const [imageSize, setImageSize] = useState({ width: 0, height: 0 })
  
  const canvasRef = useRef(null)
  const previewCanvasRef = useRef(null)
  const imageRef = useRef(null)

  const handleFileChange = (e) => {
    const file = e.target.files[0]
    if (file) {
      const url = URL.createObjectURL(file)
      setSelectedFile(url)
      
      const img = new Image()
      img.onload = () => {
        setImageSize({ width: img.width, height: img.height })
        imageRef.current = img
        handleGenerateSubtitle()
      }
      img.src = url
    }
  }

  const handleGenerateSubtitle = () => {
    if (!imageRef.current || !subtitleText) return

    const canvas = canvasRef.current
    const previewCanvas = previewCanvasRef.current
    const ctx = canvas.getContext('2d')
    const previewCtx = previewCanvas.getContext('2d')

    // 设置画布尺寸
    canvas.width = imageSize.width
    canvas.height = imageSize.height
    previewCanvas.width = imageSize.width
    previewCanvas.height = imageSize.height

    // 绘制原始图片
    ctx.drawImage(imageRef.current, 0, 0)
    previewCtx.drawImage(imageRef.current, 0, 0)

    // 设置字幕样式
    ctx.font = `${fontSize}px Arial`
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'

    // 分割文本为多行
    const lines = subtitleText.split('\n').filter(line => line.trim() !== '')
    const lineHeight = fontSize + 10 // 行高等于字体大小加上间距
    const lineSpacing = 2 // 分隔线与文本的间距
    const totalHeight = lines.length * lineHeight + (lines.length - 1) * lineSpacing

    // 计算起始Y坐标（整个字幕区域的顶部位置）
    let startY = canvas.height - subtitleHeight - totalHeight / 2

    // 逐行绘制文本和分隔线
    lines.forEach((line, index) => {
      const y = startY + index * (lineHeight + lineSpacing)

      // 绘制字幕轮廓
      ctx.strokeStyle = outlineColor
      ctx.lineWidth = 3
      ctx.strokeText(line, canvas.width / 2, y)

      // 绘制字幕文本
      ctx.fillStyle = fontColor
      ctx.fillText(line, canvas.width / 2, y)

      // 如果不是最后一行，绘制分隔线
      if (index < lines.length - 1) {
        const lineY = y + lineHeight / 2
        ctx.beginPath()
        ctx.moveTo(canvas.width / 2 - 100, lineY)
        ctx.lineTo(canvas.width / 2 + 100, lineY)
        ctx.strokeStyle = fontColor
        ctx.lineWidth = 1
        ctx.stroke()
      }
    })

    // 复制到预览画布
    previewCtx.drawImage(canvas, 0, 0)
  }

  const handleSaveImage = () => {
    if (!canvasRef.current) return

    const link = document.createElement('a')
    link.download = 'subtitle-image.png'
    link.href = canvasRef.current.toDataURL('image/png')
    link.click()
  }

  return (
    <AppContainer>
      <ConfigContainer>
        <ConfigItem>
          <Label>选择文件：</Label>
          <Input type="file" accept="image/*" onChange={handleFileChange} />
        </ConfigItem>
        <ConfigItem>
          <Label>字幕高度(px)：</Label>
          <Input 
            type="number" 
            value={subtitleHeight} 
            onChange={(e) => setSubtitleHeight(Number(e.target.value))} 
          />
        </ConfigItem>
        <ConfigItem>
          <Label>字体大小(px)：</Label>
          <Input 
            type="number" 
            value={fontSize} 
            onChange={(e) => setFontSize(Number(e.target.value))} 
          />
        </ConfigItem>
        <ConfigItem>
          <Label>字体颜色：</Label>
          <Input 
            type="color" 
            value={fontColor} 
            onChange={(e) => setFontColor(e.target.value)} 
          />
        </ConfigItem>
        <ConfigItem>
          <Label>轮廓颜色：</Label>
          <Input 
            type="color" 
            value={outlineColor} 
            onChange={(e) => setOutlineColor(e.target.value)} 
          />
        </ConfigItem>
      </ConfigContainer>

      <EditorContainer>
        <TextArea
          value={subtitleText}
          onChange={(e) => setSubtitleText(e.target.value)}
          placeholder="请输入字幕内容..."
        />
      </EditorContainer>

      <ButtonContainer>
        <Button onClick={handleGenerateSubtitle}>生成字幕</Button>
        <Button onClick={handleSaveImage}>保存图片</Button>
      </ButtonContainer>

      <PreviewContainer>
        <Canvas ref={canvasRef} />
        <PreviewCanvas ref={previewCanvasRef} />
      </PreviewContainer>
    </AppContainer>
  )
}

export default App
